package com.example.cxz2021606127.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.cxz2021606127.R;
import com.example.cxz2021606127.activity.AboutUsActivity;
import com.example.cxz2021606127.activity.LoginActivity;
import com.example.cxz2021606127.util.DataCleanManager;
import com.example.cxz2021606127.util.ToastUtil;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.textfield.TextInputEditText;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.glide.transformations.BlurTransformation;


public class PersonFragment extends Fragment {
    View view;
    ImageView imageView, ivHead;
    LinearLayout linearLayout, l1,l2;
    Button exit;
    TextView name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_person, container, false);
            ivHead = view.findViewById(R.id.iv_head);
            l1 = view.findViewById(R.id.l1);
            l2=view.findViewById(R.id.l2);
            linearLayout = view.findViewById(R.id.l4);
            imageView = view.findViewById(R.id.iv_back);
            exit = view.findViewById(R.id.btn_exit);
            name = view.findViewById(R.id.user_name);

            l2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(v.getContext(), AboutUsActivity.class);
                    startActivity(intent);
                }
            });


            /**
             * 退出登录
             */
            exit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("确定退出登录")
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .show();
                }
            });


            /**
             * 修改昵称
             */
            l1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   xiugai();
                }


            });

            /**
             * 清除缓存
             */
            linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 缓存目录为 /data/user/0/com.example.viewnews/cache
                    File file = new File(getActivity().getCacheDir().getPath());
                    System.out.println("缓存目录为：" + getActivity().getCacheDir().getPath());
                    String cacheSize = null;
                    try {
                        cacheSize = DataCleanManager.getCacheSize(file);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("缓存大小为：" + cacheSize);

                    new AlertDialog.Builder(getActivity())
                            .setTitle("提示")
                            .setMessage("当前缓存大小一共为" + cacheSize + "。确定要删除所有缓存？离线内容及其图片均会被清除。")
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // dialog 此弹窗实例共享父实例
                                    System.out.println("点击了啥内容：" + which);
                                    // 没起作用
                                    DataCleanManager.cleanInternalCache(getActivity());
                                    Toast.makeText(getActivity(), "成功清除缓存。", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .show();
                }
            });

            /**
             * 更换头像
             */
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 弹出菜单框 选择从相机拍照 还是 选择图库
                    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                    dialog.setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 判断 which 从而判断用户点击的是第几个
                            if (which == 0) {
                                // 调用系统相机权限 弹出是否同意授权
                                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);//动态申请权限

                            } else if (which == 1) {
                                // 调用系统相机 直接打开
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_PICK); // 设置跳转到相册
                                intent.setType("image/*"); // 设置类型 选图片
                                startActivityForResult(intent, 3);

                            }
                        }
                    });
                    dialog.show();

                }
            });
            Glide.with(getActivity()).load(R.drawable.tupian1)
                    .apply(RequestOptions.bitmapTransform(new BlurTransformation(15, 2)))
                    .into(imageView);
        }

        return view;
    }


    /**
     * 自定义修改昵称对话框
     */
    private void xiugai() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_xiu_gai_nick_name, null, false);
        builder.setView(view);
        Dialog dialog = builder.create();
        TextInputEditText edtMainName = (TextInputEditText) view.findViewById(R.id.edt_main_name);
        TextView tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
        TextView tvSure = (TextView) view.findViewById(R.id.tv_sure);

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nikename = edtMainName.getText().toString().trim();
                name.setText(nikename);
                Toast.makeText(getContext(), "修改成功", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    /**
     * 动态权限回调 requestCode:10 上面的requestCode
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 10) { // 系统相机申请权限返回10
            // 判断用户是否同意， PERMISSION_GRANTED = 0 : =>同意
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 调用相机activity
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); // 参数="android.media.action.IMAGE_CAPTURE"
                startActivityForResult(intent, 1); // 相机获取的数据的返回值
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            // 相机activity返回
            // 获取相机返回的图片 bitmap
            assert data != null;
            Bundle bundle = data.getExtras();
            assert bundle != null; // 调试宏，只在debug模式下有效。如果不满足条件，就会出现断言
            Bitmap bitmap = bundle.getParcelable("data");
            ivHead.setImageBitmap(bitmap);
        } else if (requestCode == 3) {
            // 获取相册返回的图片 uri对象
            Uri uri = data.getData();
            ivHead.setImageURI(uri);
        }
    }

}
